home *** CD-ROM | disk | FTP | other *** search
/ OpenGL Superbible (2nd Edition) / OpenGL SuperBible e2.iso / tools / GLUT-3.7 / PROGS / EXAMPLES / reflectdino.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-08-12  |  12.4 KB  |  406 lines

  1.  
  2. /* Copyright (c) Mark J. Kilgard, 1994, 1997.  */
  3.  
  4. /* This program is freely distributable without licensing fees 
  5.    and is provided without guarantee or warrantee expressed or 
  6.    implied. This program is -not- in the public domain. */
  7.  
  8. /* Very simple example of how to achieve reflections on a flat
  9.    surface using OpenGL blending.  The example has a mode using
  10.    OpenGL stenciling to avoid drawing the reflection not on the top of the
  11.    floor.  Initially, stenciling is not used so if you look (by holding
  12.    down the left mouse button and moving) at the dinosaur from "below"
  13.    the floor, you'll see a bogus dinosaur and appreciate how the basic
  14.    technique works.  Enable stenciling with the popup menu and the
  15.    bogus dinosaur goes away!  Also, notice that OpenGL lighting works
  16.    correctly with reflections. */
  17.  
  18. /* Check out the comments in the "redraw" routine to see how the
  19.    reflection blending and surface stenciling is done. */
  20.  
  21. /* This program is derived from glutdino.c */
  22.  
  23. /* Compile: cc -o reflectdino reflectdino.c -lglut -lGLU -lGL -lXmu -lXext -lX11 -lm */
  24.  
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <math.h>       /* for cos(), sin(), and sqrt() */
  29. #include <GL/glut.h>
  30.  
  31. typedef enum {
  32.   RESERVED, BODY_SIDE, BODY_EDGE, BODY_WHOLE, ARM_SIDE, ARM_EDGE, ARM_WHOLE,
  33.   LEG_SIDE, LEG_EDGE, LEG_WHOLE, EYE_SIDE, EYE_EDGE, EYE_WHOLE
  34. } displayLists;
  35.  
  36. GLfloat angle = 20;   /* in degrees */
  37. GLfloat angle2 = 30;   /* in degrees */
  38. int moving, startx, starty;
  39. int W = 300, H = 300;
  40. int useStencil = 0;  /* Initially, allow the artifacts. */
  41. GLdouble bodyWidth = 3.0;
  42. float jump = 0.0;
  43. /* *INDENT-OFF* */
  44. GLfloat body[][2] = { {0, 3}, {1, 1}, {5, 1}, {8, 4}, {10, 4}, {11, 5},
  45.   {11, 11.5}, {13, 12}, {13, 13}, {10, 13.5}, {13, 14}, {13, 15}, {11, 16},
  46.   {8, 16}, {7, 15}, {7, 13}, {8, 12}, {7, 11}, {6, 6}, {4, 3}, {3, 2},
  47.   {1, 2} };
  48. GLfloat arm[][2] = { {8, 10}, {9, 9}, {10, 9}, {13, 8}, {14, 9}, {16, 9},
  49.   {15, 9.5}, {16, 10}, {15, 10}, {15.5, 11}, {14.5, 10}, {14, 11}, {14, 10},
  50.   {13, 9}, {11, 11}, {9, 11} };
  51. GLfloat leg[][2] = { {8, 6}, {8, 4}, {9, 3}, {9, 2}, {8, 1}, {8, 0.5}, {9, 0},
  52.   {12, 0}, {10, 1}, {10, 2}, {12, 4}, {11, 6}, {10, 7}, {9, 7} };
  53. GLfloat eye[][2] = { {8.75, 15}, {9, 14.7}, {9.6, 14.7}, {10.1, 15},
  54.   {9.6, 15.25}, {9, 15.25} };
  55. GLfloat lightZeroPosition[] = {10.0, 14.0, 10.0, 1.0};
  56. GLfloat lightZeroColor[] = {0.8, 1.0, 0.8, 1.0}; /* green-tinted */
  57. GLfloat lightOnePosition[] = {-1.0, 1.0, 1.0, 0.0};
  58. GLfloat lightOneColor[] = {0.6, 0.3, 0.2, 1.0}; /* red-tinted */
  59. GLfloat skinColor[] = {0.1, 1.0, 0.1, 1.0}, eyeColor[] = {1.0, 0.2, 0.2, 1.0};
  60. /* *INDENT-ON* */
  61.  
  62. void
  63. extrudeSolidFromPolygon(GLfloat data[][2], unsigned int dataSize,
  64.   GLdouble thickness, GLuint side, GLuint edge, GLuint whole)
  65. {
  66.   static GLUtriangulatorObj *tobj = NULL;
  67.   GLdouble vertex[3], dx, dy, len;
  68.   int i;
  69.   int count = dataSize / (int) (2 * sizeof(GLfloat));
  70.  
  71.   if (tobj == NULL) {
  72.     tobj = gluNewTess();  /* create and initialize a GLU
  73.                              polygon tesselation object */
  74.     gluTessCallback(tobj, GLU_BEGIN, glBegin);
  75.     gluTessCallback(tobj, GLU_VERTEX, glVertex2fv);  /* semi-tricky */
  76.     gluTessCallback(tobj, GLU_END, glEnd);
  77.   }
  78.   glNewList(side, GL_COMPILE);
  79.   glShadeModel(GL_SMOOTH);  /* smooth minimizes seeing
  80.                                tessellation */
  81.   gluBeginPolygon(tobj);
  82.   for (i = 0; i < count; i++) {
  83.     vertex[0] = data[i][0];
  84.     vertex[1] = data[i][1];
  85.     vertex[2] = 0;
  86.     gluTessVertex(tobj, vertex, data[i]);
  87.   }
  88.   gluEndPolygon(tobj);
  89.   glEndList();
  90.   glNewList(edge, GL_COMPILE);
  91.   glShadeModel(GL_FLAT);  /* flat shade keeps angular hands
  92.                              from being "smoothed" */
  93.   glBegin(GL_QUAD_STRIP);
  94.   for (i = 0; i <= count; i++) {
  95.     /* mod function handles closing the edge */
  96.     glVertex3f(data[i % count][0], data[i % count][1], 0.0);
  97.     glVertex3f(data[i % count][0], data[i % count][1], thickness);
  98.     /* Calculate a unit normal by dividing by Euclidean
  99.        distance. We * could be lazy and use
  100.        glEnable(GL_NORMALIZE) so we could pass in * arbitrary
  101.        normals for a very slight performance hit. */
  102.     dx = data[(i + 1) % count][1] - data[i % count][1];
  103.     dy = data[i % count][0] - data[(i + 1) % count][0];
  104.     len = sqrt(dx * dx + dy * dy);
  105.     glNormal3f(dx / len, dy / len, 0.0);
  106.   }
  107.   glEnd();
  108.   glEndList();
  109.   glNewList(whole, GL_COMPILE);
  110.   glFrontFace(GL_CW);
  111.   glCallList(edge);
  112.   glNormal3f(0.0, 0.0, -1.0);  /* constant normal for side */
  113.   glCallList(side);
  114.   glPushMatrix();
  115.   glTranslatef(0.0, 0.0, thickness);
  116.   glFrontFace(GL_CCW);
  117.   glNormal3f(0.0, 0.0, 1.0);  /* opposite normal for other side */
  118.   glCallList(side);
  119.   glPopMatrix();
  120.   glEndList();
  121. }
  122.  
  123. void
  124. makeDinosaur(void)
  125. {
  126.   extrudeSolidFromPolygon(body, sizeof(body), bodyWidth,
  127.     BODY_SIDE, BODY_EDGE, BODY_WHOLE);
  128.   extrudeSolidFromPolygon(arm, sizeof(arm), bodyWidth / 4,
  129.     ARM_SIDE, ARM_EDGE, ARM_WHOLE);
  130.   extrudeSolidFromPolygon(leg, sizeof(leg), bodyWidth / 2,
  131.     LEG_SIDE, LEG_EDGE, LEG_WHOLE);
  132.   extrudeSolidFromPolygon(eye, sizeof(eye), bodyWidth + 0.2,
  133.     EYE_SIDE, EYE_EDGE, EYE_WHOLE);
  134. }
  135.  
  136. void
  137. drawDinosaur(void)
  138. {
  139.   glPushMatrix();
  140.   glTranslatef(0.0, jump, 0.0);
  141.   glMaterialfv(GL_FRONT, GL_DIFFUSE, skinColor);
  142.   glCallList(BODY_WHOLE);
  143.   glPushMatrix();
  144.   glTranslatef(0.0, 0.0, bodyWidth);
  145.   glCallList(ARM_WHOLE);
  146.   glCallList(LEG_WHOLE);
  147.   glTranslatef(0.0, 0.0, -bodyWidth - bodyWidth / 4);
  148.   glCallList(ARM_WHOLE);
  149.   glTranslatef(0.0, 0.0, -bodyWidth / 4);
  150.   glCallList(LEG_WHOLE);
  151.   glTranslatef(0.0, 0.0, bodyWidth / 2 - 0.1);
  152.   glMaterialfv(GL_FRONT, GL_DIFFUSE, eyeColor);
  153.   glCallList(EYE_WHOLE);
  154.   glPopMatrix();
  155.   glPopMatrix();
  156. }
  157.  
  158. void
  159. drawFloor(void)
  160. {
  161.   glDisable(GL_LIGHTING);
  162.   glBegin(GL_QUADS);
  163.     glVertex3f(-18.0, 0.0, 27.0);
  164.     glVertex3f(27.0, 0.0, 27.0);
  165.     glVertex3f(27.0, 0.0, -18.0);
  166.     glVertex3f(-18.0, 0.0, -18.0);
  167.   glEnd();
  168.   glEnable(GL_LIGHTING);
  169. }
  170.  
  171. void
  172. redraw(void)
  173. {
  174.   if (useStencil) {
  175.     /* Clear; default stencil clears to zero. */
  176.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  177.   } else {
  178.     /* Not using stencil; just clear color and depth. */
  179.     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  180.   }
  181.  
  182.   glPushMatrix();
  183.     /* Perform scene rotations based on user mouse input. */
  184.     glRotatef(angle2, 1.0, 0.0, 0.0);
  185.     glRotatef(angle, 0.0, 1.0, 0.0);
  186.  
  187.     /* Translate the dinosaur to be at (0,0,0). */
  188.     glTranslatef(-8, -8, -bodyWidth / 2);
  189.  
  190.     glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition);
  191.     glLightfv(GL_LIGHT1, GL_POSITION, lightOnePosition);
  192.  
  193.     if (useStencil) {
  194.      
  195.       /* We can eliminate the visual "artifact" of seeing the "flipped"
  196.      dinosaur underneath the floor by using stencil.  The idea is
  197.      draw the floor without color or depth update but so that 
  198.      a stencil value of one is where the floor will be.  Later when
  199.      rendering the dinosaur reflection, we will only update pixels
  200.      with a stencil value of 1 to make sure the reflection only
  201.      lives on the floor, not below the floor. */
  202.  
  203.       /* Don't update color or depth. */
  204.       glDisable(GL_DEPTH_TEST);
  205.       glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
  206.  
  207.       /* Draw 1 into the stencil buffer. */
  208.       glEnable(GL_STENCIL_TEST);
  209.       glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
  210.       glStencilFunc(GL_ALWAYS, 1, 0xffffffff);
  211.  
  212.       /* Now render floor; floor pixels just get their stencil set to 1. */
  213.       drawFloor();
  214.  
  215.       /* Re-enable update of color and depth. */ 
  216.       glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  217.       glEnable(GL_DEPTH_TEST);
  218.  
  219.       /* Now, only render where stencil is set to 1. */
  220.       glStencilFunc(GL_EQUAL, 1, 0xffffffff);  /* draw if ==1 */
  221.       glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
  222.     }
  223.  
  224.     glPushMatrix();
  225.  
  226.       /* The critical reflection step: Reflect dinosaur through the floor
  227.          (the Y=0 plane) to make a relection. */
  228.       glScalef(1.0, -1.0, 1.0);
  229.  
  230.       /* Position lights now in reflected space. */
  231.       glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition);
  232.       glLightfv(GL_LIGHT1, GL_POSITION, lightOnePosition);
  233.  
  234.       /* XXX Ugh, unfortunately the back face culling reverses when we reflect
  235.      the dinosaur.  Easy solution is just disable back face culling for
  236.      rendering the reflection.  Also, the normals for lighting get screwed
  237.      up by the scale; enabled normalize to ensure normals are still
  238.      properly normalized despite the scaling.  We could have fixed the
  239.      dinosaur rendering code, but this is more expedient. */
  240.       glEnable(GL_NORMALIZE);
  241.       glCullFace(GL_FRONT);
  242.  
  243.       /* Draw the reflected dinosaur. */
  244.       drawDinosaur();
  245.  
  246.       /* Disable noramlize again and re-enable back face culling. */
  247.       glDisable(GL_NORMALIZE);
  248.       glCullFace(GL_BACK);
  249.  
  250.     glPopMatrix();
  251.  
  252.     /* Restore light positions on returned from reflected space. */
  253.     glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition);
  254.     glLightfv(GL_LIGHT1, GL_POSITION, lightOnePosition);
  255.  
  256.  
  257.     if (useStencil) {
  258.       /* Don't want to be using stenciling for drawing the actual dinosaur
  259.      (not its reflection) and the floor. */
  260.       glDisable(GL_STENCIL_TEST);
  261.     }
  262.  
  263.     /* Back face culling will get used to only draw either the top or the
  264.        bottom floor.  This let's us get a floor with two distinct
  265.        appearances.  The top floor surface is reflective and kind of red.
  266.        The bottom floor surface is not reflective and blue. */
  267.  
  268.     /* Draw "top" of floor.  Use blending to blend in reflection. */
  269.     glEnable(GL_BLEND);
  270.     glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  271.     glColor4f(0.7, 0.0, 0.0, 0.3);
  272.     drawFloor();
  273.     glDisable(GL_BLEND);
  274.  
  275.     /* Draw "bottom" of floor in blue. */
  276.     glFrontFace(GL_CW);  /* Switch face orientation. */
  277.     glColor4f(0.1, 0.1, 0.7, 1.0);
  278.     drawFloor();
  279.     glFrontFace(GL_CCW);
  280.  
  281.     /* Draw "actual" dinosaur, not its reflection. */
  282.     drawDinosaur();
  283.  
  284.   glPopMatrix();
  285.  
  286.   glutSwapBuffers();
  287. }
  288.  
  289. /* ARGSUSED2 */
  290. void
  291. mouse(int button, int state, int x, int y)
  292. {
  293.   if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
  294.     moving = 1;
  295.     startx = x;
  296.     starty = y;
  297.   }
  298.   if (button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
  299.     moving = 0;
  300.   }
  301. }
  302.  
  303. /* ARGSUSED1 */
  304. void
  305. motion(int x, int y)
  306. {
  307.   if (moving) {
  308.     angle = angle + (x - startx);
  309.     angle2 = angle2 + (y - starty);
  310.     startx = x;
  311.     starty = y;
  312.     glutPostRedisplay();
  313.   }
  314. }
  315.  
  316. GLboolean lightZeroSwitch = GL_TRUE, lightOneSwitch = GL_TRUE;
  317.  
  318. void
  319. controlLights(int value)
  320. {
  321.   switch (value) {
  322.   case 1:
  323.     lightZeroSwitch = !lightZeroSwitch;
  324.     if (lightZeroSwitch) {
  325.       glEnable(GL_LIGHT0);
  326.     } else {
  327.       glDisable(GL_LIGHT0);
  328.     }
  329.     break;
  330.   case 2:
  331.     lightOneSwitch = !lightOneSwitch;
  332.     if (lightOneSwitch) {
  333.       glEnable(GL_LIGHT1);
  334.     } else {
  335.       glDisable(GL_LIGHT1);
  336.     }
  337.     break;
  338.   case 3:
  339.     useStencil = 1 - useStencil;
  340.     break;
  341.   }
  342.   glutPostRedisplay();
  343. }
  344.  
  345. void
  346. idle(void)
  347. {
  348.   static float time;
  349.  
  350.   time = glutGet(GLUT_ELAPSED_TIME) / 500.0;
  351.  
  352.   jump = 3.0 * fabs(sin(time));
  353.   glutPostRedisplay();
  354. }
  355.  
  356. void 
  357. visible(int vis)
  358. {
  359.   if (vis == GLUT_VISIBLE)
  360.     glutIdleFunc(idle);
  361.   else
  362.     glutIdleFunc(NULL);
  363. }
  364.  
  365. int
  366. main(int argc, char **argv)
  367. {
  368.   glutInit(&argc, argv);
  369.   glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
  370.   glutCreateWindow("Leapin' Lizards");
  371.   glutDisplayFunc(redraw);
  372.   glutMouseFunc(mouse);
  373.   glutMotionFunc(motion);
  374.   glutVisibilityFunc(visible);
  375.   glutCreateMenu(controlLights);
  376.   glutAddMenuEntry("Toggle right light", 1);
  377.   glutAddMenuEntry("Toggle left light", 2);
  378.   glutAddMenuEntry("Toggle stenciling out reflection artifacts", 3);
  379.   glutAttachMenu(GLUT_RIGHT_BUTTON);
  380.   makeDinosaur();
  381.   glEnable(GL_CULL_FACE);
  382.   glEnable(GL_DEPTH_TEST);
  383.   glEnable(GL_LIGHTING);
  384.   glMatrixMode(GL_PROJECTION);
  385.   gluPerspective( /* field of view in degree */ 40.0,
  386.   /* aspect ratio */ 1.0,
  387.     /* Z near */ 1.0, /* Z far */ 80.0);
  388.   glMatrixMode(GL_MODELVIEW);
  389.   gluLookAt(0.0, 0.0, 40.0,  /* eye is at (0,0,30) */
  390.     0.0, 0.0, 0.0,      /* center is at (0,0,0) */
  391.     0.0, 1.0, 0.);      /* up is in postivie Y direction */
  392.   glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, 1);
  393.   glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor);
  394.   glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1);
  395.   glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05);
  396.   glLightfv(GL_LIGHT1, GL_DIFFUSE, lightOneColor);
  397.   glEnable(GL_LIGHT0);
  398.   glEnable(GL_LIGHT1);
  399.  
  400.     glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition);
  401.     glLightfv(GL_LIGHT1, GL_POSITION, lightOnePosition);
  402.  
  403.   glutMainLoop();
  404.   return 0;             /* ANSI C requires main to return int. */
  405. }
  406.